package dht.message;
import dht.*;
import java.nio.ByteBuffer;

public abstract class PaxosMessage extends Message {

    // 2 bytes for OpCode and 4 bytes for proposalNumber
    private static final int SIZE = 2 + 4;
    private byte[] bytes;

    @Override
    public byte[] getBytes() {
        synchronized (this) {
            if (bytes == null) {
                bytes = ByteBuffer.allocate(SIZE).putShort(getOpCode().value()).putInt(proposalNumber).array();
            }
            return bytes;
        }
    }
    private final int proposalNumber;

    public int getProposalNumber() {
        return proposalNumber;
    }

    public PaxosMessage(OpCode opCode, int proposalNumber, HostAddress addr) {
        super(opCode, addr);
        this.proposalNumber = proposalNumber;
    }

    public PaxosMessage(byte[] message, HostAddress addr) {
        super(message, addr);
        this.proposalNumber = getProposalNumberFromBytes(message);
    }

    public static int getProposalNumberFromBytes(byte[] bytes) {
        if (bytes.length < (2 + 4)) {
            throw new IllegalArgumentException(
                    "Paxos messages start with OpCode (2 bytes)"
                    + "and then proposal number ( 4 bytes )");
        }
        return ByteBuffer.wrap(bytes).getInt(2);
    }

    @Override
    public String toString() {
        return getOpCode() + " with proposal# : " + getProposalNumber();
    }
}
